# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 12:56:53 2013

@author: jkwong
"""

#PBAR_BasicZSPEC_SCNtoCSV.py
import os
import sys
import numpy as np

def PBAR_BasicZSPEC_SCNtoCSV(arg):
    """Creates ZSPEC csv files from a scan file"""
    MAXFILES = 2500
    
    # parse arguments
    scnDir, dataDir, imgNumber = arg

    # mkdir for the csv files
    csvDir = os.path.join(dataDir, imgNumber)
    if os.path.exists(csvDir):
        print('csv directory already exists: %s' %csvDir)
    else:
        cmmd = r'mkdir %s' %csvDir
        print('Make directory for csv files: %s' %cmmd)
        os.mkdir(csvDir)

    print("asfdasdfasdf")
    # make the command for convert the scn to img
    # command looks like this:
    #  /home/dastest/program/imaging/pbarSf2Img -o ~/vxWorks/jkwong/4761.img /home/dastest/program/imaging/p_4761.scn

    commandFullFilename = os.path.join(scnDir, 'pbarSf2Img')
    imgFilename = '%s.img' % imgNumber
    imgFullFilename =  os.path.join(csvDir, imgFilename)
    
    scnFilename = 'p_%s.scn' % imgNumber
    scnFullFilename =  os.path.join(scnDir, scnFilename)

    cmmd = r'%s -o %s %s' %(commandFullFilename, imgFullFilename, scnFullFilename)
    print('Create img file: %s' % imgFullFilename)
    print (cmmd)
    os.system(cmmd)
    
    # img to csv
    # example:
    #  /home/dastest/program/imaging/smg.ancore.com-rawImgToCsv.exe32 -o 4761 -img FDFC ~/vxWorks/jkwong/4761.img -range 0 2500
    currentPath = os.getcwd()
    os.chdir(csvDir)
    commandFullFilename = os.path.join(scnDir, 'smg.ancore.com-rawImgToCsv.exe32')
    cmmd = '%s -o %s -img FDFC %s -range 0 %d' %(commandFullFilename, imgNumber, imgFullFilename, MAXFILES)
    print('Creating cvs files')    
    print(cmmd)
    os.system(cmmd)
    os.chdir(currentPath)
    print('Done.')
    

def PBAR_BasicZSPEC_SCNtoNumpy(arg):
    """Creates ZSPEC csv files from a scan file"""
    MAXFILES = 2500
    NumberDetectors = 136
    NumberEnergyBins = 32
    
    # parse arguments
    scnDir, dataDir, imgNumber = arg

    # mkdir for the csv files
    csvDir = os.path.join(dataDir, imgNumber)
    if os.path.exists(csvDir):
        print('csv directory already exists: %s' %csvDir)
    else:
        cmmd = r'mkdir %s' %csvDir
        print('Make directory for csv files: %s' %cmmd)
        os.mkdir(csvDir)
    
    # make the command for convert the scn to img
    # command looks like this:
    #  /home/dastest/program/imaging/pbarSf2Img -o ~/vxWorks/jkwong/4761.img /home/dastest/program/imaging/p_4761.scn

    commandFullFilename = os.path.join(scnDir, 'pbarSf2Img')
    imgFilename = '%s.img' % imgNumber
    imgFullFilename =  os.path.join(csvDir, imgFilename)
    
    scnFilename = 'p_%s.scn' % imgNumber
    scnFullFilename =  os.path.join(scnDir, scnFilename)

    cmmd = r'%s -o %s %s' %(commandFullFilename, imgFullFilename, scnFullFilename)
    print('Create img file: %s' % imgFullFilename)
    print (cmmd)
    os.system(cmmd)
    
    # img to csv
    # example:genfromtxt
    #  /home/dastest/program/imaging/smg.ancore.com-rawImgToCsv.exe32 -o 4761 -img FDFC ~/vxWorks/jkwong/4761.img -range 0 2500
    currentPath = os.getcwd()
    os.chdir(csvDir)
    commandFullFilename = os.path.join(scnDir, 'smg.ancore.com-rawImgToCsv.exe32')
    cmmd = '%s -o %s -img FDFC %s -range 0 %d' %(commandFullFilename, imgNumber, imgFullFilename, MAXFILES)
    print('Creating cvs files')
    print(cmmd)
    os.system(cmmd)
    os.chdir(currentPath)
    print('Done.')
    
    # convert the csv to numpy data format.  Not saving the energy array
    # bulid the file name
    dat = np.zeros((MAXFILES, NumberEnergyBins, NumberDetectors))
    for i in xrange(MAXFILES):
        filename = '%s-FDFC-slice%d.csv' %(imgNumber, i)
        fullFilename = os.path.join(csvDir, filename)
        print(fullFilename)
        if os.path.exists(fullFilename):
            try:
                temp = np.genfromtxt(fullFilename, skip_header = 3, delimiter = ',')
                dat[i,:,:] = temp[:,1:137]
            except:
                print('Problem')
                break
        else:
            print('File does not exist. Stopping.')
            break
    dat = dat[0:i,:,:]
    dat = dat.astype(np.uint16)
    filename = '%s-FDFC-All%d' %(imgNumber, i)
    np.save(os.path.join(csvDir, filename), dat)
    print('Saved: %s' %os.path.join(csvDir, filename))
    

if __name__ == '__main__':
#    PBAR_BasicZSPEC_SCNtoCSV(sys.argv[1:])
    PBAR_BasicZSPEC_SCNtoNumpy(sys.argv[1:])   
